﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ServiceInterfaces.Stores;
using DTO.Common;
using System.ServiceModel;

namespace GUI.Stores
{
    public partial class _Default : System.Web.UI.Page
    {
        protected int currPage = 1;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["page"]))
            {
                int.TryParse(Request.QueryString["page"], out currPage);
            }

            int nRegbyPage = int.Parse(ddl_nRegistos.SelectedValue);

            PageControlTop.ResultsPerPage = nRegbyPage;
            PageControlTop.CurrentPage = currPage;

            if (IsPostBack)
            {
                Control cause = GetPostBackControl(this);
                if (cause.ID != "bt_comprar")
                {
                    ProductList productsList = obterdados(currPage, nRegbyPage);

                    GV_Produtos.DataSource = productsList.Products;
                    GV_Produtos.DataBind();

                    // número total de registos na base de dados
                    PageControlTop.TotalResults = productsList.Total; 
                }
                             
            }
            else
            {
                ProductList productsList = obterdados(currPage, nRegbyPage);

                GV_Produtos.DataSource = productsList.Products;
                GV_Produtos.DataBind();

                // número total de registos na base de dados
                PageControlTop.TotalResults = productsList.Total;       
            }

        }

        private ProductList obterdados(int page, int recordsPerPage)
        {
            ProductList productsList;

            try
            {
                ChannelFactory<IStoreSales> factory = new ChannelFactory<IStoreSales>("store");
                IStoreSales store = factory.CreateChannel();
                productsList = store.GetProducts(page, recordsPerPage);
                factory.Close();

            }
            catch (Exception)
            {
                throw;
            }

            return productsList;
        }

        protected void bt_comprar_Click(object sender, EventArgs e)
        {

            List<SoldProduct> soldProduct = new List<SoldProduct>();

            foreach (GridViewRow row in GV_Produtos.Rows)
            {

                CheckBox cb_buy = (CheckBox)row.FindControl("cb_buy");
                TextBox tb_qtd = (TextBox)row.FindControl("tb_qtd");
                int qtd = int.Parse(tb_qtd.Text);

                if (cb_buy.Checked && qtd > 0)
                {
                    HiddenField hf_code = (HiddenField)row.FindControl("hf_code");
                    SoldProduct sp = new SoldProduct();
                    Product prd = new Product();
                    prd.Code = int.Parse(hf_code.Value);
                    sp.Product = prd;
                    sp.Amount = qtd;

                    soldProduct.Add(sp);
                }
            }

            bool success = comprarProdutos(soldProduct);
            if (success)
            {
                Server.Transfer("~/Success.aspx");
            }
            else
            {
                HttpContext.Current.Items["produtos"] = soldProduct;
                Server.Transfer("~/ErrorProduct.aspx", true);
            }

        }


        

        private bool comprarProdutos(List<SoldProduct> soldProduct)
        {
            ChannelFactory<IStoreSales> factory = new ChannelFactory<IStoreSales>("store");

            try
            {
                IStoreSales store = factory.CreateChannel();
                store.Sell(soldProduct);
                factory.Close();

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        protected void ddl_nRegistos_SelectedIndexChanged(object sender, EventArgs e)
        {
            PageControlTop.ResultsPerPage = Int32.Parse(ddl_nRegistos.SelectedValue);

        }


        public static Control GetPostBackControl(Page page)
        {
            Control postbackControlInstance = null;

            string postbackControlName = page.Request.Params.Get("__EVENTTARGET");
            if (postbackControlName != null && postbackControlName != string.Empty)
            {
                postbackControlInstance = page.FindControl(postbackControlName);
            }
            else
            {
                // handle the Button control postbacks
                for (int i = 0; i < page.Request.Form.Keys.Count; i++)
                {
                    postbackControlInstance = page.FindControl(page.Request.Form.Keys[i]);
                    if (postbackControlInstance is System.Web.UI.WebControls.Button)
                    {
                        return postbackControlInstance;
                    }
                }
            }

            return postbackControlInstance;
        }
    }
}